package sdu.acs.connections;

import gnu.io.*;
import java.util.*;
import java.io.*;

public class RFIDConnection {
	private static CommPortIdentifier serialPortID = null;
	private static SerialPort serialPort = null;
	private static InputStream in = null;

	public static boolean connect() {
		System.out.print("Connecting to RFID... ");
		if (serialPort == null) {
			try {
				Enumeration enumcomm = CommPortIdentifier.getPortIdentifiers();
				while (enumcomm.hasMoreElements()) {
					serialPortID = (CommPortIdentifier) enumcomm.nextElement();
					if (serialPortID.getPortType() == CommPortIdentifier.PORT_SERIAL) {
						System.out
								.print("Trying to connect to RFID with PORT: "
										+ serialPortID.getName() + "... ");
					}
				}
				serialPort = (SerialPort) serialPortID
						.open("serial talk", 1000);
				serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		try {
			in = serialPort.getInputStream();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static long nextCard() {
		long card = 0;
		for (int i = 0; i < 13; i++) {
			try {
				card = card * 10 + ((char) in.read()) - '0';
			} catch (Exception e) {
				e.printStackTrace();
				return -1;
			}
		}
		return card;
	}

	public static boolean nextAvailable() {
		try {
			if (in.available() > 0) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}
}
